package com.demo.wormhole.component.mvc.interceptor;

import com.demo.wormhole.core.context.WormholeContext;
import com.demo.wormhole.core.context.WormholeContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;

/**
 * 链路跟踪Request设置值
 */
public class MvcWormholeWebInterceptor implements WebRequestInterceptor {
    
    @Override
    public void preHandle(WebRequest webRequest) {
        //失效上下文，解决Tomcat线程复用问题
        WormholeContextHolder.invalidContext();
        String wormholeValue = webRequest.getHeader(WormholeContextHolder.WORMHOLE_REQUEST_MARK);
        if (StringUtils.isNotEmpty(wormholeValue)) {
            WormholeContextHolder.setContext(new WormholeContext(wormholeValue));
        }
    }
    
    @Override
    public void postHandle(WebRequest webRequest, ModelMap modelMap) throws Exception {
        
    }
    
    @Override
    public void afterCompletion(WebRequest webRequest, Exception e) throws Exception {
        
    }
}
